package com.example.demo2.service.impl;

import com.example.demo2.entity.ComparisonResults;
import com.example.demo2.mapper.ComparisonResultsMapper;
import com.example.demo2.service.ComparisonResultsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @version 1.0
 * @description TODO
 * @date 2024/7/9 22:39
 */
@Service
public class ComparisonResultsServiceImpl implements ComparisonResultsService {
    private static final Logger logger = LoggerFactory.getLogger(ComparisonResultsServiceImpl.class);
    @Autowired
    private ComparisonResultsMapper comparisonResultsMapper;

    @Override
    public Page<ComparisonResults> getComparisonResultsByName(String comparisonName, int page, int size) {
        try {
            int offset = page * size;
            List<ComparisonResults> results = comparisonResultsMapper.findByComparisonName(comparisonName, offset, size);
            long total = comparisonResultsMapper.countByComparisonName(comparisonName);

            logger.info("Fetched {} results for comparison name: {}", results.size(), comparisonName);

            return new PageImpl<>(results, PageRequest.of(page, size), total);
        } catch (Exception e) {
            logger.error("Error fetching comparison results for name: " + comparisonName, e);
            throw new RuntimeException("Error fetching comparison results", e);
        }
    }
}
